import { message } from "ant-design-vue"

export async function apiFetch<T>(
  url: string,
  options: RequestInit = {}
): Promise<T> {
  const token = localStorage.getItem('token')

  const headers = new Headers(options.headers || {})
  headers.set('Content-Type', 'application/json')

  if (token) {
    headers.set('Authorization', `Bearer ${token}`)
  }

  const res = await fetch(url, {
    ...options,
    headers
  })
  if (res.status === 401) {
    message.error("请先登录")
    // 例如跳转登录
    window.location.href = "/login"
    throw new Error("Unauthorized")
  }

  if (res.status === 403) {
    message.error("您没有权限访问该资源")
    throw new Error("Forbidden")
  }
  if (!res.ok) {
    throw new Error(`请求失败: ${res.status}`)
  }

  return res.json() as Promise<T>
}
